<template>
  <el-dialog
    :visible="showDialog"
    title="新增/编辑"
    :close-on-click-modal="false"
    top="8vh"
    @close="closeDialog"
    @click.native="closeTree"
  >
    <el-form
      ref="form"
      label-width="160px"
      :model="formData"
      :rules="formRules"
    >
      <el-form-item label="姓名：" prop="username">
        <el-input
          v-model="formData.username"
          style="width: 440px"
          placeholder="1-30字符"
        />
      </el-form-item>
      <el-form-item label="手机：" prop="mobile">
        <el-input
          v-model="formData.mobile"
          style="width: 440px"
          placeholder="请输入手机号"
        />
      </el-form-item>
      <el-form-item label="入职时间：" prop="timeOfEntry">
        <el-date-picker
          v-model="formData.timeOfEntry"
          type="date"
          placeholder="选择日期"
          style="width: 220px"
          value-format="yyyy-MM-dd"
        />
      </el-form-item>
      <el-form-item label="聘用形式：" prop="formOfEmployment">
        <el-select
          v-model="formData.formOfEmployment"
          style="width: 440px"
          placeholder="请选择"
        >
          <el-option
            v-for="item in hireType"
            :key="item.id"
            :label="item.value"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="工号：" prop="workNumber">
        <el-input
          v-model="formData.workNumber"
          style="width: 440px"
          placeholder="1-20字符"
        />
      </el-form-item>
      <el-form-item label="部门：" prop="departmentName">
        <el-input
          :value="formData.departmentName"
          style="width: 440px"
          placeholder="请选择"
          @click.native.stop="handleDepartments"
        />
        <div v-if="treeShow" class="tree-box">
          <el-tree
            v-loading="loading"
            node-key="id"
            :data="treeData"
            :props="{ label: 'name' }"
            style="width: 440px"
            @node-click="nodeClick"
          />
        </div>
      </el-form-item>
      <el-form-item label="转正时间：" prop="correctionTime">
        <el-date-picker
          v-model="formData.correctionTime"
          type="date"
          placeholder="选择日期"
          style="width: 220px"
          value-format="yyyy-MM-dd"
        />
      </el-form-item>
      <el-row type="flex" justify="center">
        <el-button type="primary" size="small" @click="btnOk">提交</el-button>
        <el-button size="small" @click="closeDialog">取消</el-button>
      </el-row>
    </el-form>
  </el-dialog>
</template>
<script>
import { getDepartmentListApi } from '@/api/departments'
import { addEmployeesApi } from '@/api/employees'
import Employees from '@/constant/employees'
export default {
  data() {
    return {
      // 控制dialog的显示或隐藏
      showDialog: false,
      formData: {
        // 入职时间
        timeOfEntry: '',
        // 转正时间
        correctionTime: '',
        // 员工名字
        username: '',
        // 手机号
        mobile: '',
        // 员工聘用形式
        formOfEmployment: null,
        // 员工工号
        workNumber: '',
        // 部门
        departmentName: ''
      },
      // 表单校验
      formRules: {
        username: [{ required: true, message: '请输入', trigger: 'blur' }],
        mobile: [{ required: true, message: '请输入', trigger: 'blur' }],
        timeOfEntry: [{ required: true, message: '请选择', trigger: 'change' }],
        formOfEmployment: [
          { required: true, message: '请选择', trigger: 'change' }
        ],
        workNumber: [{ required: true, message: '请输入', trigger: 'blur' }],
        departmentName: [
          { required: true, message: '请选择', trigger: 'change' }
        ],
        correctionTime: [
          { required: true, message: '请选择', trigger: 'change' }
        ]
      },
      // 部门树形数据
      treeData: [],
      // 控制部门显示隐藏
      treeShow: false,
      loading: false,
      // 聘用形式的枚举数据
      hireType: Employees.hireType
    }
  },
  computed: {},
  created() {},
  methods: {
    closeDialog() {
      this.showDialog = false
      this.$refs.form.resetFields()
    },
    // 处理部门数据方法
    async handleDepartments() {
      // 点击显示隐藏树
      this.treeShow = !this.treeShow
      this.loading = true
      const res = await getDepartmentListApi()
      this.treeData = this.transListToTreeData(res.data.depts, '')
      this.loading = false
    },
    // 点击dialog 可以关闭部门树
    closeTree() {
      this.treeShow = false
    },
    nodeClick(value) {
      // 判断选择是否是当前部门的最后一个层级
      if (value.children && value.children.length > 0) return

      this.formData.departmentName = value.name
      this.treeShow = false
    },
    /**
     * !使用递归方法，将扁平数据改变成树状数据
     */
    transListToTreeData(list, searchVal) {
      // list 接收的是数据， searchVal 接收的表示一级的id
      const arr = []
      // 遍历查找一级
      list.forEach((item) => {
        if (item.pid === searchVal) {
          // 调用transListToTreeData函数查找2级
          const children = this.transListToTreeData(list, item.id)
          item.children = children
          // push 一级
          arr.push(item)
        }
      })
      return arr
    },
    // 添加员工
    async btnOk() {
      try {
        await this.$refs.form.validate()
      } catch (error) {
        return console.log(error)
      }
      await addEmployeesApi(this.formData)
      this.$message.success('添加成功')
      this.closeDialog()
      this.$emit('updata')
    }
  }
}
</script>

<style lang="scss" scoped>
.tree-box {
  position: absolute;
  width: 50%;
  min-height: 50px;
  left: 0;
  top: 45px;
  z-index: 100;
  border: 1px solid #ccc;
  border-radius: 4px;
  padding-right: 5px;
  overflow: hidden;
  background-color: #fff;
  max-height: 200px;
  overflow: auto;
  ::v-deep {
    .el-tree-node__content {
      height: auto;
    }
  }
}
</style>
